<template>
  <div class="map-wrapper">
    <!-- 搜索面板 -->
    <div class="search-panel">
      <el-input 
        v-model="searchText" 
        placeholder="请输入搜索关键字" 
        id="searchInputId"
        class="search-input"
      />
      <el-input 
        v-model="startName" 
        placeholder="起始地点"
        id="startInputId"
        class="location-input"
      />
      <el-select v-model="rule" class="route-select">
        <el-option
          v-for="item in routeRules"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          placeholder="请选择驾车算路策略"
        />
      </el-select>
      <el-button @click="goView" class="search-btn">搜索</el-button>
      <el-button @click="clearAll" class="clear-btn">清除</el-button>
    </div>

    <!-- 路线规划面板 -->
    <div class="route-panel" v-if="routeArr.length > 0">
      <div class="route-header">
        <div class="route-title">
          路线规划策略：{{ policy }}
        </div>
        <el-button 
          icon="Close" 
          size="mini" 
          circle 
          class="close-btn"
          @click="clearRoute"
        />
      </div>
      <div class="route-content">
        <el-row
          v-for="(item, index) in routeArr"
          :key="index"
          class="route-step"
        >
          <span class="step-index">{{ index + 1 }}</span>
          <span class="step-instruction">{{ item.instruction }}</span>
        </el-row>
      </div>
    </div>

    <!-- 地图容器 -->
    <div id="amap" class="map-container"></div>
    
    <!-- 结果面板 -->
    <!-- <div 
      id="panel" 
      class="result-panel"
      :class="{ 'result-panel-closed': !isResultPanelVisible }"
    >
      <div class="result-header">
        <div class="result-title">搜索结果</div>
        <el-button 
          icon="Close" 
          size="mini" 
          circle 
          class="close-btn"
          @click="toggleResultPanel"
        />
      </div>
      <div class="result-body" v-show="isResultPanelVisible">
        
      </div>
      <div class="result-toggle" @click="toggleResultPanel" v-show="!isResultPanelVisible">
        <span>结果面板</span>
        <el-icon><ArrowRight /></el-icon>
      </div>
    </div> -->
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getCommunityAddress } from "@/api/communityDetail";
import { useRoute } from 'vue-router'; 
import { ElMessage } from 'element-plus';
import { ArrowRight } from '@element-plus/icons-vue';

const route = useRoute();
const comId = route.params.comId;

// 高德地图安全配置
window._AMapSecurityConfig = {
  securityJsCode: "13699e5f65c4aed04394f1bb12f6bb8a",
};

// 响应式变量
const searchText = ref('');
const startName = ref('');
const endName = ref('');
const rule = ref(32); // 默认策略
const routeArr = ref([]);
const policy = ref('');
const longitude = ref(''); // 默认经度
const latitude = ref(''); // 默认纬度
const routeRules = [
  { value: 0, label: '速度优先' },
  { value: 1, label: '费用优先' },
  { value: 2, label: '距离优先' },
  { value: 41, label: '躲避拥堵＋少收费' },
  { value: 32, label: '默认' },
];

// 结果面板控制
const isResultPanelVisible = ref(true);

// 地图相关变量
let map: any = null;
let AMapObj: any = null;
let geocoder: any = null;
let driving: any = null;
let marker: any = null;
let currentRoute: any = null;
let startAutoComplete: any = null;

// 初始化地图
onMounted(() => {
  initMap();
  // 获取社区地址信息
  getCommunityAddress({ comId: comId }).then(res => {
    endName.value = res.data.market + res.data.region + res.data.details;
    longitude.value = res.data.longitude;
    latitude.value = res.data.latitude;

  });
});

// 初始化地图
async function initMap() {
  await AMapLoader.load({
    key: '233623ecf4f7652ac57140a8bc1ed775',
    version: '2.0',
    plugins: [
      'AMap.ToolBar', 'AMap.Scale', 'AMap.Geolocation',
      'AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.HawkEye',
      'AMap.MapType', 'AMap.CircleEditor', 'AMap.MouseTool',
      'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Driving'
    ],
  }).then(AMap => {
    AMapObj = AMap;
    map = new AMap.Map('amap', {
      zoom: 12,
      resizeEnable: true,
      center: [104.065306, 30.658017], // 成都经纬度
      viewMode: "3D",
    });

    // 添加地图控件
    map.addControl(new AMap.ToolBar({ position: 'LT' }));
    map.addControl(new AMap.Scale());
    map.addControl(new AMap.HawkEye());
    map.addControl(new AMap.MapType());
    map.addControl(new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      buttonPosition: 'LB',
      showMarker: true,
      showCircle: true,
      panToLocation: true,
      zoomToAccuracy: true
    }));

    // 初始化地理编码器
    geocoder = new AMap.Geocoder({ city: '全国' });

    // 实现输入提示
    initAutoComplete();
    // 创建终点标记
    createMarker();
    
    // 为起始地点添加输入提示
    initStartAutoComplete();
  });
}

// 初始化搜索框输入提示
function initAutoComplete() {
  const autoOptions = { input: 'searchInputId' };
  const auto = new AMapObj.AutoComplete(autoOptions);
  const placeSearch = new AMapObj.PlaceSearch({
    map: map,
    pageSize: 5,
    pageIndex: 1,
    autoFitView: true,
    panel: "panel"
  });
  auto.on("select", (e: any) => {
    placeSearch.search(e.poi.name);
  });
}

// 初始化起始地点输入提示
function initStartAutoComplete() {
  const autoOptions = { input: 'startInputId' };
  startAutoComplete = new AMapObj.AutoComplete(autoOptions);
  
  startAutoComplete.on("select", (e: any) => {
    startName.value = e.poi.name;
    console.log('起始地点选择:', e.poi);
  });
}

// 创建标记点
function createMarker() {
  // 清除已有标记
  if (marker) map.remove(marker);
  
  const lonNum = Number(longitude.value);
  const latNum = Number(latitude.value);
  const position = new AMapObj.LngLat(lonNum, latNum);
  
  marker = new AMapObj.Marker({
    position: position,
    content: `
      <div class="custom-marker">
        <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">
        <div class="close-btn">×</div>
      </div>
    `,
    offset: new AMapObj.Pixel(-13, -30),
  });
  
  map.add(marker);
  map.setCenter(position);
  
  // 绑定关闭事件
  setTimeout(() => {
    const closeBtn = document.querySelector(".close-btn");
    if (closeBtn) {
      closeBtn.addEventListener('click', () => clearMarker());
    }
  }, 100);
}

// 清除标记
function clearMarker() {
  if (marker) {
    map.remove(marker);
    marker = null;
  }
}

// 路线规划
const goView = () => {
  if (!startName.value || !endName.value) {
    ElMessage.warning('请输入起始地点和目的地点');
    return;
  }
  
  // 清除已有路线
  if (driving) driving.clear();
  
  driving = new AMapObj.Driving({
    map,
    policy: rule.value
  });
  
  const points = [
    { keyword: startName.value, city: '兰州' },
    { keyword: endName.value, city: '兰州' }
  ];
  
  driving.search(points, (status: string, result: any) => {
    if (status === 'complete') {
      routeArr.value = result.routes[0].steps;
      policy.value = result.routes[0].policy;
      currentRoute = result;
      ElMessage.success('路线规划成功');
    } else {
      ElMessage.error('路线规划失败，请检查输入');
    }
  });
};

// 清除路线
const clearRoute = () => {
  if (driving) driving.clear();
  routeArr.value = [];
  policy.value = '';
  currentRoute = null;
};

// 一键清除所有
const clearAll = () => {
  clearRoute();
  clearMarker();
  startName.value = '';
  searchText.value = '';
};

// 切换结果面板显示/隐藏
const toggleResultPanel = () => {
  isResultPanelVisible.value = !isResultPanelVisible.value;
};

// 清理地图实例
onUnmounted(() => {
  if (map) map.destroy();
});
</script>

<style scoped lang="less">
.map-wrapper {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.map-container {
  width: 100%;
  height: 100%;
}

// 搜索面板样式
.search-panel {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  display: flex;
  gap: 10px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
}

.search-input {
  width: 220px;
}

.location-input {
  width: 180px;
}

.el-select {
  width: 160px;
}

.search-btn {
  background-color: #1677ff;
  border-color: #1677ff;
}

.clear-btn {
  background-color: #f5f5f5;
  color: #666;
  border-color: #ddd;
}

// 结果面板样式
.result-panel {
  position: absolute;
  top: 100px;
  right: 20px;
  z-index: 999;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  
  &.result-panel-closed {
    width: 60px !important;
    height: 60px !important;
    
    .result-header, .result-body {
      display: none;
    }
    
    .result-toggle {
      display: flex !important;
      align-items: center;
      justify-content: center;
      height: 100%;
      cursor: pointer;
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      
      span {
        writing-mode: vertical-rl;
        text-orientation: mixed;
        margin-right: 5px;
        font-size: 12px;
        color: #333;
      }
      
      .el-icon {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.result-header {
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-title {
  font-weight: 500;
  color: #333;
}

.result-body {
  height: calc(100vh - 160px);
  width: 300px;
  overflow-y: auto;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 10px;
  box-sizing: border-box;
}

.result-toggle {
  display: none;
}

// 路线面板样式 - 位置下移
.route-panel {
  position: absolute;
  top: 160px; // 下移60px，避免遮挡地图控件
  left: 20px;
  width: 360px;
  z-index: 9999;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  max-height: calc(100% - 180px);
  display: flex;
  flex-direction: column;
}

.route-header {
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.route-title {
  font-weight: 500;
  color: #333;
}

.close-btn {
  color: #999;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
  
  &:hover {
    background-color: #eee;
    color: #666;
  }
}

.route-content {
  padding: 10px 0;
  overflow-y: auto;
  max-height: 400px;
}

.route-step {
  padding: 10px 16px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  align-items: flex-start;
  font-size: 14px;
  transition: background-color 0.2s;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:hover {
    background-color: #f9f9f9;
  }
}

.step-index {
  display: inline-block;
  width: 20px;
  height: 20px;
  background-color: #1677ff;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  margin-right: 10px;
  flex-shrink: 0;
  margin-top: 2px;
}

.step-instruction {
  color: #666;
  line-height: 1.5;
}

// 自定义标记样式
.custom-marker {
  position: relative;
  
  .close-btn {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 16px;
    height: 16px;
    background-color: #ff4d4f;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 16px;
    font-size: 12px;
    cursor: pointer;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  }
}
</style>